module manager {

    export class StatisticsManager extends egret.DisplayObjectContainer {

        public static readonly domain: string = "https://2zhuji.cn";
        public static readonly login_key: string = "game_userinfo2";
        public static readonly coin_key: string = "game_coin";
        public static readonly uv_key: string = "game_tunnel_uv";

        public appToken: string;
        public options: any = {};
        public host: Host = new Host();
        private loginData: LoginData = new LoginData();

        public shareTickets = "";

        public authMask: egret.Sprite;
        public authButton;


        public static sceneId: number = 0;

        public static readonly LOAD_APPLIST_COMPLETE: string = "load_applist_complete";
        public static readonly jump_key: string = "jump_tunnel_uv";
        public static readonly list_uv_key: string = "game_list_uv";
        public static readonly commit_id = 51213;
        public static readonly game_id = '260536';
        public constructor(appToken: string) {
            super();
            this.appToken = appToken;
        }
        private had_stats = false;
        public static navigateToMiniProgramAppIdList = [
            "wxfc88730de46e6d73",
            "wxe34b9a6fb6d6a683",
            "wxeff665b7aeb9c57c",
            "wxd82f35a30b912252",
            "wx60a23c9c93a7d3e9",
            "wx0a767065c320c201",
            "wx9d8b7327f15aef96",
            "wxa5d198883633db4d",
            "wx904ebc01fa813399",
            "wx66facba7a8d32b7a"
        ];

        //统计渠道
        public statsTunnel() {
            //统计uv
            let is_new = manager.GameManager.getInstance().getUserManager().new_user;
            let options = wx.getLaunchOptionsSync() || {};
            options = options["query"];
            if (!options["wxa_tunnel"] || !this.appToken || this.had_stats) return;
            this.had_stats = true;
            let wxa_tunnel = options["wxa_tunnel"]
            let uv;
            let that = this;
            wx.getStorage({
                key: StatisticsManager.uv_key,
                success: function (res) {
                },
                fail: function (res) {
                },
                complete: function (res) {
                    let time = new Date();
                    let timeFormat = time.getFullYear() + "-"
                        + (time.getMonth() + 1) + "-"
                        + time.getDate();
                    let obj = res.data;
                    if (obj) {
                        if (res.data["uv" + wxa_tunnel] == timeFormat) {
                            uv = 0;
                        } else {
                            uv = 1;
                            obj["uv" + wxa_tunnel] = timeFormat;
                            UtilsManager.setStore(StatisticsManager.uv_key, obj);
                        }
                    } else {
                        uv = 1;
                        let obj = {};
                        obj["uv" + wxa_tunnel] = timeFormat;
                        UtilsManager.setStore(StatisticsManager.uv_key, obj);
                    }
                    let postData: PostData = new PostData();
                    postData.tunnel_id = wxa_tunnel;
                    //postData.wecha_id = that.host.wecha_id;
                    postData.token = that.appToken;
                    if (uv) {
                        postData["uv"] = 1;
                    }
                    if (is_new) {
                        postData["is_new"] = 1;
                    }
                    if (options["from_wecha"]) {
                        postData.from_wecha = options["from_wecha"];
                    }
                    if (options["from_appid"]) {
                        postData.from_appid = options["from_appid"];
                    }
                    console.log("statsTunnel:", postData);
                    let request = new egret.HttpRequest();
                    request.responseType = egret.HttpResponseType.TEXT;
                    let url: string = StatisticsManager.domain
                        + '/index.php?g=Wap&m=WxaDistribution&a=pv_statistics';
                    request.open(url, egret.HttpMethod.GET);
                    request.setRequestHeader("Content-Type", "application/json");
                    request.send(postData);
                    request.addEventListener(egret.Event.COMPLETE, that.onLoadComplete, that);
                    request.addEventListener(egret.IOErrorEvent.IO_ERROR, that.onPostIOError, that);
                }
            })
        }

        public static click(eventId: number): void {
            let request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            let url: string = StatisticsManager.domain
                + '/index.php?g=WxaGame&m=Statistic&a=event_stat_click&id=' + eventId;
            request.open(url, egret.HttpMethod.GET);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.send();
        }

        public static hideAtScene(sceneId: number): void {
            let appToken = manager.GameManager.getInstance().getAppToken();
            let session_3rd = manager.GameManager.getInstance().session_3rd;
            let request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            let url: string = StatisticsManager.domain
                + '/index.php?g=WxaGame&m=WxaGameCount&token=' + appToken + '&session_3rd=' + session_3rd + '&a=sceneCount&scene=' + sceneId;
            request.open(url, egret.HttpMethod.GET);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.send();
        }

        public static playLevel(level: number): void {
            let app_token = manager.GameManager.getInstance().getAppToken();
            let session_3rd = manager.GameManager.getInstance().session_3rd;
            let request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            let url: string = StatisticsManager.domain
                + '/index.php?g=Wxa&m=RecordLevel&a=recordLevel&session_3rd=' + session_3rd + '&app_token=' + app_token + '&level=' + level;
            request.open(url, egret.HttpMethod.GET);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.send();
        }

        private onLoadComplete(event: egret.Event): void {
            let request = <egret.HttpRequest>event.currentTarget;
            console.log(JSON.parse(request.response));
        }

        private onPostIOError(event: egret.IOErrorEvent): void {
            console.log("post error : " + event);
        }

        //点击渠道统计
        public statusPv(appid, path, app_id, fromB = false) {
            //统计应用列表中跳转其他小程序的应用pv
            if (( !fromB && ((path.indexOf('?wxa_tunnel') != -1 || path.indexOf('&wxa_tunnel') != -1) && path.indexOf('path=') === -1))
                ||(fromB && (path.indexOf('wxa_tunnel') != -1))
            ) {
                //a-c,b-c
                path = decodeURIComponent(path);
                let wxa_tunnel = manager.StatisticsManager.getParaFromPath("wxa_tunnel", path);
                this.statsTunnelPv({
                    wxa_tunnel: wxa_tunnel,
                    appid: appid,
                    path: path,
                    from_token: this.appToken
                })
                //return;
            }
            // if (!appid) {
            //     return;
            // }
            this.statsAppPv(app_id);
        }

        public statsAppPv(id) {
            if (!id) {
                console.log("stats error:no id!");
                return;
            }
            this.statsRetention(id);
            var date = new Date();
            var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            var uv;
            let that = this;
            wx.getStorage({
                key: "app_uv",
                success: function (res) {},
                fail: function (res) {},
                complete: function (res) {
                    console.log(res.data);
                    var obj = res.data;
                    if (obj) {
                        if (res.data["uv" + id] == time) {
                            uv = 0;
                        } else {
                            uv = 1;
                            obj["uv" + id] = time;
                            wx.setStorage({
                                key: "app_uv",
                                data: obj,
                                success: function(res){},
                                fail: function(res){},
                                complete: function(res){}
                            });
                        }
                    } else {
                        uv = 1;
                        obj = {};
                        obj["uv" + id] = time;
                        wx.setStorage({
                            key: "app_uv",
                            data: obj,
                            success: function(res){},
                            fail: function(res){},
                            complete: function(res){}
                        });
                    }
                    var tail = "";
                    if (uv) {
                        tail = "&uv=1";
                    }
                    wx.request({
                        url: 'https://2zhuji.cn/index.php?g=Wap&m=Outerapi&a=get_wxa_pv&id=' + id + '&token=' + that.appToken + tail,
                        method: 'GET',
                        data: {},
                        header: {
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        dataType: 'json',
                        success: function (res) {
                            console.log("stats:" + id + " success! uv:" + uv);
                        },
                        fail: function(res){},
                        complete: function(res){}
                    });
                }
            });
        }

        private statsRetention(id) {
            if (!id || !GameManager.getInstance().session_3rd) {
                return;
            }
            var that = this;
            var rt, id = id;
            var date = new Date();
            var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            wx.getStorage({
                key: "app_retention",
                complete: function (res) {
                    console.log(res.data);
                    var obj = res.data;
                    if (obj) {
                        if (res.data["rt" + id] == time) {
                            rt = 0;
                        } else {
                            rt = 1;
                        }
                    } else {
                        rt = 1;
                        obj = {};
                    }
                    if (rt) {
                        obj["rt" + id] = time;
                        wx.setStorage({
                            key: "app_retention",
                            data: obj,
                            success: function(res){},
                            fail: function(res){},
                            complete: function(res){}
                        });
                        var post_data = {
                            game_id: id,
                            commit_id: manager.StatisticsManager.commit_id,
                            token: this.appToken
                        }
                        // if (that.host.sex) {
                        //     post_data["sex"] = that.host.sex;
                        // }
                        if (Number(manager.GameManager.getInstance().getUserManager().new_user)) {
                            post_data["new_user"] = 1;
                        }
                        wx.request({
                            url: 'https://2zhuji.cn/index.php?g=Wxa&m=WxaLoginStat&a=stat_retention&session_3rd=' + GameManager.getInstance().session_3rd,
                            method: 'POST',
                            data: post_data,
                            header: {
                                'content-type': 'application/json'
                            },
                            dataType: 'json',
                            success: function (res) {
                                console.log("statsRetention " + id + " success!");
                            },
                            fail: function(res){},
                            complete: function(res){}
                        });
                    }
                },
                success: function(res){},
                fail: function(res){}
            })
        }

        public statsTunnelPv(options) {
            if (Main.getInstance().gameManager.getUserManager().host.wecha_id) {
                this.statsTunnelPv2(options)
            }
        }

        private statsTunnelPv2(options) {
            let that = this;
            let wxa_tunnel = options.wxa_tunnel;
            let appid = options.appid;
            let path = decodeURIComponent(options.path);
            var uv;
            //that.goToMiniPro(appid, path)
            wx.getStorage({
                key: StatisticsManager.jump_key,
                success: function(res) {},
                fail: function(res) {},
                complete: function(res) {
                    var date = new Date();
                    var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                    var obj = res.data;
                    if (obj) {
                        if (res.data["uv" + wxa_tunnel] == time) {
                            uv = 0;
                        } else {
                            uv = 1;
                            obj["uv" + wxa_tunnel] = time;
                            wx.setStorage({
                                key: StatisticsManager.jump_key,
                                data: obj,
                                success: function(res) {},
                                fail: function(res) {},
                                complete: function(res) {}
                            })
                        }
                    } else {
                        uv = 1;
                        obj = {};
                        obj["uv" + wxa_tunnel] = time;
                        wx.setStorage({
                            key: StatisticsManager.jump_key,
                            data: obj,
                            success: function(res) {},
                            fail: function(res) {},
                            complete: function(res) {}
                        })
                    }
                    statsPv()
                }
            })

            function statsPv() {
                let send_data = {
                    session_3rd: GameManager.getInstance().session_3rd,
                    tunnel_id: wxa_tunnel,
                    commit_id: manager.StatisticsManager.commit_id,
                    token: that.appToken,
                    wecha_id: GameManager.getInstance().getUserManager().host["wecha_id"]
                }
                if (uv) {
                    send_data["uv"] = uv;
                }
                if (options.from_wecha) {
                    send_data["from_wecha"] = options.from_wecha;
                }
                if (Number(manager.GameManager.getInstance().getUserManager().new_user)) {
                    send_data["is_new"] = 1;
                }
                let para = wx.getLaunchOptionsSync();
                if (para && para.query && para.query.from_token) {
                    send_data["from_wxa"] = para.query.from_token;
                }
                wx.request({
                    url: 'https://2zhuji.cn/index.php?g=Wap&m=WxaDistribution&a=jump_pv',
                    method: 'GET',
                    header: {
                        'content-type': 'application/json'
                    },
                    data: send_data,
                    dataType: "json",
                    success: function() {
                        console.log("statsTunnelPv", send_data)
                    },
                    fail: function(res) {},
                    complete: function(res) {}
                })
            }
        }

        public statsListClick(game_id) {
            //统计游戏列表的点击次数
            if (!this.appToken || !game_id) return
            wx.request({
                url: 'https://2zhuji.cn/index.php?g=Wxa&m=ListStat&a=stat_for_click',
                method: 'GET',
                header: {
                    'content-type': 'application/json'
                },
                data: {
                    token: this.appToken,
                    mat_id: game_id
                },
                dataType: 'json',
                success: function() {},
                fail: function(res) {},
                complete: function(res) {}
            });
        }

        public statsTunnelClickFrom(path, adType, ad_id, sysAd) {
            if (path.indexOf('wxa_tunnel') == -1) return;
            let index = path.indexOf('wxa_tunnel');
            let str = path.substring(index);
            if (str.indexOf('&') > 0) {
                let idx = str.indexOf('&');
                str = str.substring(0, idx);
            }
            let wxa_tunnel = str.split('=')[1];
            if (!wxa_tunnel) return;
            let send_data = {
                tunnel_id: wxa_tunnel,
                token: this.appToken,
                ad_type: adType,
                ad_id: ad_id
            }
            if (sysAd) {
                send_data["sysAd"] = 1;
            }
            wx.request({
                url: 'https://2zhuji.cn/index.php?g=Wap&m=WxaDistribution&a=click_from',
                method: 'POST',
                data: send_data,
                header: {
                    'content-type': 'application/json'
                },
                dataType: 'json',
                success: function(res) {
                    if (res.data.status == 1001) {
                        console.log('statsTunnelClickFrom', send_data)
                    }
                },
                fail: function(res) {},
                complete: function(res) {}
            })
        }

        public adStats(click, type, obj: any = {}) {
            if (click && obj.type == "1") {
                this.statsTunnelClickFrom(obj.path, type, obj.ad_id ? obj.ad_id : obj.id, obj.ad_id && !obj.id ? 1 : 0)
            }
            if (click && !obj.id) {
                this.sysAdStats(obj);
                return;
            }
            if (!click && !obj.type) {
                obj = manager.GameManager.auditData[type + "ad"];
            }
            var that = this, header = {'content-type': 'application/x-www-form-urlencoded'};
            var post_data = {
                token: this.appToken,
                type: type
            }
            if (obj && obj.id) {
                post_data["id"] = obj.id;
            }
            if (obj && obj.relation_id) {
                post_data["relation_id"] = obj.relation_id;
            }
            if (!click) {
                if (type == "banner" || type == "menu" || type == "gameFloat" || type == "drawer"  || type == "gdt" || type == "notice" || ( (type == "ad") && (Array.isArray(obj)) )) {
                    var arr = [], ids = [], rids = [];
                    arr = manager.GameManager.auditData[type + "ad"] || [];
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i].id) {
                            ids.push(arr[i].id);
                        }
                        if (arr[i].relation_id) {
                            rids.push(arr[i].relation_id);
                        }
                    }
                    if (arr && arr.length) {
                        post_data["arr"] = ids;
                    }
                    if (rids && rids.length) {
                        post_data["relation_arr"] = rids;
                    }
                }
                header = {'content-type': 'application/json'}
            }
            if (click) {
                post_data["click"] = 1;
            }
            wx.request({
                url: 'https://2zhuji.cn/index.php?g=Wap&m=Wxa&a=float_count',
                method: "get",
                data: post_data,
                header: header,
                dataType: 'json',
                success: function (res) {
                    // if (click && obj) {
                    //     navToAd(obj);
                    // }
                },
                fail: function(res) {},
                complete: function(res) {}
            });
        }

        public sysAdStats(obj) {
            if (!obj.ad_id) {
                console.log("system ad stats error:no ad_id");
                //navToAd(obj);
                return;
            }
            var date = new Date();
            var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            wx.getStorage({
                key: "app_sysAd",
                complete: function (res) {
                    var uv = 1;
                    var data = res.data;
                    if (data && (data[obj.ad_id] == time)) {
                        uv = 0;
                    } else {
                        data = data || {};
                        data[obj.ad_id + ""] = time;
                        wx.setStorage({
                            key: "app_sysAd",
                            data: data,
                            success: function(res) {},
                            fail: function(res) {},
                            complete: function(res) {}
                        });
                    }
                    var post_data = {
                        commit_id: manager.StatisticsManager.commit_id,
                        token: this.appToken,
                        ad_id: obj.ad_id
                    }
                    if (uv) {
                        post_data["uv"] = 1;
                    }
                    if (obj.cur_game_id) {
                        post_data["game_id"] = obj.cur_game_id;
                    }
                    // if (app.host.sex) {
                    //     post_data["sex"] = app.host.sex;
                    // }
                    wx.request({
                        url: 'https://2zhuji.cn/index.php?g=Wxa&m=WxaStat&a=wxa_ad_click',
                        method: "get",
                        data: post_data,
                        header: {'content-type': 'application/x-www-form-urlencoded'},
                        dataType: 'json',
                        success: function (res) {
                            console.log("sys ad stats ok:", obj.ad_id, " uv:", uv);
                            //navToAd(obj);
                        },
                        fail: function(res) {},
                        complete: function(res) {}
                    });
                },
                success: function (res) {},
                fail: function(res) {}
            })
        }

        public getListStorage (datas) {
            if (!datas || !datas.length) return
            let that  = this
            var mat_arr = [];
            for (var i = 0; i < datas.length; i++) {
                mat_arr.push(datas[i].id)
            }
            var uv;
            wx.getStorage({
                key: StatisticsManager.list_uv_key,
                complete: function (res) {
                    var date = new Date();
                    var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                    var obj = res.data;
                    if (obj) {
                        if (res.data["uv_" + time] === time) {
                            uv = 0;
                        } else {
                            uv = 1;
                            obj["uv_" + time] = time;
                            wx.setStorage({
                                key: StatisticsManager.list_uv_key,
                                data: obj,
                                success: function(res) {},
                                fail: function(res) {},
                                complete: function(res) {}
                            })
                        }
                    } else {
                        uv = 1;
                        obj = {};
                        obj["uv_" + time] = time;
                        wx.setStorage({
                            key: StatisticsManager.list_uv_key,
                            data: obj,
                            success: function(res) {},
                            fail: function(res) {},
                            complete: function(res) {}
                        })
                    }
                    that.statsListPv(mat_arr, uv)
                },
                success: function(res) {},
                fail: function(res) {}
            })
        }

        private statsListPv(mat_arr, uv) {
            //统计游戏列表的展示pv、uv
            if (!this.appToken || !mat_arr.length) return;
            wx.request({
                url: 'https://2zhuji.cn/index.php?g=Wxa&m=ListStat&a=stat_for_pv' + (uv ? '&uv=1' : '') + '&token=' + this.appToken,
                method: 'POST',
                header: {
                    'content-type': 'application/json'
                },
                data: {
                    mat_arr: mat_arr
                },
                dataType: 'json',
                success: function (res) {},
                fail: function(res) {},
                complete: function(res) {}
            })
        }

        public static checkAppList (appid) {
            if (GameManager.auditData.jump_img_off == "1") return true
            if (StatisticsManager.navigateToMiniProgramAppIdList && StatisticsManager.navigateToMiniProgramAppIdList.length) {
                let arr = StatisticsManager.navigateToMiniProgramAppIdList
                for (var i = 0; i < arr.length; i++) {
                    if (appid == arr[i]) {
                        return true
                    }
                }
            }
            return false
        }

        public static getParaFromPath (para, path) {
            if (!para || !path) return
            let re = "";
            path = decodeURIComponent(path)
            if (path && path.indexOf(para + "=") != -1) {
                let index = path.indexOf(para + "=")
                path = path.substring(index);
                let arr = path.split("&")
                re = arr[0].replace(para + "=", "")
            }
            return re
        }

        public static goToMiniPro(data, callback): void {
            console.log("jump:", {appid: data.appid, path: data.path});
            if (!manager.StatisticsManager.checkAppList(data.appid)) {
                let img = manager.StatisticsManager.getParaFromPath("img", data.path);
                if (img) {
                    helper.Helper.previewImg(img);
                    return;
                }
            }
            wx.navigateToMiniProgram({
                appId: data.appid,
                path: data.path,
                extraData: {},
                success: function(res){
                    if (callback) callback();
                },
                fail: function(res){},
                complete: function(res){}
            });
        }

        public static sceneCount(eventId: number): void {
            let request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            let url: string = StatisticsManager.domain
                + '/index.php?g=WxaGame&m=WxaGameCount&a=sceneCount'
                + '&scene=' + eventId
                + '&token=' + manager.GameManager.getInstance().getAppToken()
                + '&session_3rd=' +  manager.GameManager.getInstance().getUserManager().loginData.session_3rd;
            request.open(url, egret.HttpMethod.GET);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.send();
        }
    }



    export class PostData {
        public tunnel_id: string;
        public wecha_id: string;
        public token: string;
        public from_wecha: string;
        public from_appid: string;
        public new_user: string;
    }

    export class LoginData {

        public encryptedData: string;

        public iv: string;

        public session_3rd: string;

        public new_user: string;
    }

    export class Host {
        public name: string;
        public portrait: string;
        public unionid: string;
        public wecha_id: string;
        public province: string;
        public city: string;
        public sex: string;
        public user: User;
        public userinfo: any;

    }

    export class User {
        public id: number;
        public money: number;
        public diamond: number;
        public wecha_id: string;
    }

}